package yxy.game.pm2.command.dungeon;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.DungeonMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.dungeon.DungeonModule;
import yxy.game.pm2.module.dungeon.DungeonStage;
import yxy.game.pm2.module.dungeon.DungeonType;

import java.util.Map;

/** 日常副本 副本进度获取 */
@MessageType(proto = Command.DungeonProgressAcquire, classtype = DungeonMessage.DungeonProgressAcquireRequest.class)
public class CMD_DungeonProgressAcquire extends Command<DungeonMessage.DungeonProgressAcquireRequest> {

	@Override
	public void execute(MessageSource messageSource, DungeonMessage.DungeonProgressAcquireRequest request) {
		String playerCode = messageSource.getTag();

		DungeonMessage.DungeonProgressAcquireResponse.Builder response = DungeonMessage.DungeonProgressAcquireResponse.newBuilder();

		try {
			Map<DungeonType, DungeonModule> dungeons = DungeonModule.all(playerCode);
			for (DungeonModule dungeon : dungeons.values()) {
				DungeonMessage.Dungeon.Builder builder = DungeonMessage.Dungeon.newBuilder();
				builder.setOpen(dungeon.isOpen());
				builder.setType(dungeon.getType().getNumber());
				builder.setFreetimes(dungeon.freeTimes());
				builder.setPaytimes(dungeon.payTimes());
				builder.setCost(new CurrencyHandle().packItem(dungeon.cost(1)));
				if (dungeon.isOpen()) {
					for (DungeonStage stage : dungeon.getStages()) {
						DungeonMessage.DungeonStage.Builder stagebuilder = DungeonMessage.DungeonStage.newBuilder();
						stagebuilder.setId(stage.getId());
						stagebuilder.setState(DungeonMessage.DungeonStageState.forNumber(stage.getState().getNumber()));
						builder.addStages(stagebuilder);
					}
				}

				response.addDungeons(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}

	}

	private void send(MessageSource messageSource, DungeonMessage.DungeonProgressAcquireResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}